package com.cci.kangdao.dao;

import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderT;
import com.cci.kangdao.escalation.dto.request.GetWorkOrderListRequest;
import com.cci.kangdao.escalation.dto.response.GetWorkOrderListResponse;
import com.cci.kangdao.model.condition.CloseWorkOrderCondition;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;
import java.util.Map;

/**
 * 工单类dao
 *
 */
@MapperScan
public interface WorkOrderTDao {
	//根据工单id获取工单信息
	@Select("select * from WorkOrder_T where ID = #{orderId}")
	Map<String, Object> getOrderById(@Param("orderId") long orderId);

	//根据工单编号获取工单
	@Select("select * from WorkOrder_T a where a.Flag = 0 and a.OrderNo = #{orderNo}")
	Map<String,Object> getOrderByNo(@Param("orderNo") String orderNo);

	//获取dcec和xcec待技师接单工单      获取指派技师时间到当前时间分钟数
	@Select("select DATEDIFF(MINUTE,a.AssignEngineerTime,#{systime}) as OverTime,a.*,b.StationName from WorkOrder_T a\n" +
            "left join ServiceStation_T b on a.ServiceStationId = b.ID\n" +
            "where a.OrderStatus=#{orderstatus} and a.OrderChannel in(3,4)")
	public List<Map<String, Object>> getAssignEngineerTimeWorkOrderTByOrderStatus(Map<String, Object> map);

	//获取dcec和xcec技师已接单外出工单      获取技师接单时间到当前时间分钟数
    @Select("select DATEDIFF(MINUTE,a.ReceiveTimeEngineer,#{systime}) as OverTime,a.*,b.StationName from WorkOrder_T a\n" +
            "left join ServiceStation_T b on a.ServiceStationId = b.ID\n" +
            "where a.OrderStatus=#{orderstatus} and a.OrderChannel in(3,4) and a.IsOutside = 1")
	public List<Map<String, Object>> getReceiveTimeEngineerWorkOrderTByOrderStatus(Map<String, Object> map);


	//用户在线报修/用户联系CSC热线/CSC工单改派,区域服务经理超时15分钟   工单默认通过，修改工单信息
    @Update("UPDATE WorkOrder_T set OrderStatus=#{OrderStatus},UpdateTime=#{updateTime},AssignStationTime=#{updateTime},isShowStation=#{isShowStation}\r\n" +
			" WHERE OrderNo=#{OrderNo} and UpdateTime=#{UpdateTime}")
	public int updatePassWorkOrderByUser(Map<String, Object> map);

	//服务站APP报修/服务站CRM报修,区域服务经理超时15分钟   工单默认通过，修改工单信息
    @Update("UPDATE WorkOrder_T set OrderStatus=#{OrderStatus},UpdateTime=#{updateTime},AssignStationTime=#{updateTime} ,isShowStation=#{isShowStation}\r\n" +
			" WHERE OrderNo=#{OrderNo} and UpdateTime=#{UpdateTime}")
	public int updatePassWorkOrderByServerStation(Map<String, Object> map);

	//关闭工单(根据工单主键id修改工单表中工单状态，关闭时间，关闭原因，修改人，修改时间)
	@Update("update WorkOrder_T set OrderStatus=#{OrderStatus},CloseTime=#{CloseTime},CloseReason=#{CloseReason},Updator=#{Updator},UpdateTime=#{UpdateTime} where ID=#{ID} and UpdateTime=#{OldUpdateTime}")
	public int updateCloseWorkOrderById(Map<String, Object> map);

	//关闭工单(根据工单主键id修改工单表中工单状态，关闭时间，关闭原因，修改人，修改时间)
	@Update("update WorkOrder_T set OrderStatus=#{OrderStatus},CloseTime=#{CloseTime},CloseReason=#{CloseReason},Updator=#{Updator},UpdateTime=#{UpdateTime},isShowStation=#{isShowStation} where ID=#{ID} and UpdateTime=#{OldUpdateTime}")
	public int updateCloseIsShowWorkOrderById(Map<String, Object> map);


	@Update("update WorkOrder_T set OrderStatus=#{status}, updator = #{updator}, updateTime = #{updateTime} where id = #{id}")
	int updateWorkOrderStatusById(CloseWorkOrderCondition condition);


	//根据WorkOrderT主键id获取工单信息
	@Select("select * from WorkOrder_T where Flag = 0 and ID=#{ID}")
	public WorkOrderT getWorkOrderTById(Map<String, Object> map);


	@Select("select * from WorkOrder_T where Flag = 0 and ID = #{orderId}")
	WorkOrderT getWorkOrderByOrderId(@Param("orderId") Long orderId);


	int insertWorkOrderSelective(WorkOrderT workOrder);


	//根据WorkOrderT主键orderId获取工单信息
	@Select("select * from WorkOrder_T where Flag = 0 and ID=#{orderId}")
	public WorkOrderT getWorkOrderTByOrderId(@Param("orderId") long orderId);


	//服务站指派服务技师时，修改工单相关信息(根据工单主键id修改工单表中服务车id，服务车编号，指派服务技师时间，当前负责人id，工单状态，修改人，修改时间)
	@Update({"<script>",
			"update WorkOrder_T set " +
			"<when test='GoOutType!=null'>",
			"GoOutType= #{GoOutType},",
			"</when>",
			"<when test='ServiceCarId!=null'>",
			"ServiceCarId= #{ServiceCarId},",
			"</when>",
			"<when test='ServiceCarNo!=null'>",
			"ServiceCarNo=#{ServiceCarNo},",
			"</when>",
			"<when test='EmergencyMode!=null'>",
			"EmergencyMode=#{EmergencyMode},",
			"</when>",
			"<when test='ServiceStationId!=null'>",
			"ServiceStationId=#{ServiceStationId},",
			"</when>",
			"AssignEngineerTime=#{AssignEngineerTime},PrincipalId =#{PrincipalId},OrderStatus =#{OrderStatus},\r\n" +
			"Updator=#{Updator},UpdateTime=#{UpdateTime} where ID =#{ID} and UpdateTime=#{OldUpdateTime}",
			"</script>"})
	public int updateZPServiceTechnician(Map<String, Object> map);

	//服务站指派服务技师时，修改工单相关信息(根据工单主键id修改工单表中是否外出状态，工单状态，修改人，修改时间)
	@Update({"<script>",
	    "update WorkOrder_T set ",
	    "<when test='IsOutside!=null'>",
	    "IsOutside=#{IsOutside},",
	    "</when>",
		"<when test='ServiceInitPlan!=null'>",
		"ServiceInitPlan=#{ServiceInitPlan},",
		"</when>",
	    "ReceiveTimeStation=#{ReceiveTimeStation},OrderStatus=#{OrderStatus},Updator=#{Updator},UpdateTime=#{UpdateTime} where ID =#{ID} and UpdateTime=#{oldUpdateTime}",
	    "</script>"})
	public int receiveWorkOrder(Map<String, Object> map);

	//服务站拒绝工单
	@Update("update WorkOrder_T set RefuseTimeStation=#{RefuseTimeStation},RefuseReasonStation=#{RefuseReasonStation},OrderStatus=#{OrderStatus},Updator=#{Updator},UpdateTime=#{UpdateTime} where ID=#{ID} and UpdateTime=#{OldUpdateTime}")
	public int updateServiceStationRefuseWorkOrder(Map<String, Object> map);

	//服务技师开始维修，维修完成和用户app评价完成后修改工单状态
	//@Update("update WorkOrder_T set OrderStatus=#{OrderStatus},Updator=#{Updator},UpdateTime=#{UpdateTime} where ID=#{ID}")
	@Update({"<script>",
			"update WorkOrder_T",
			"<set>",
            "<if test='takeSteps != null'>",
            "TakeSteps = #{takeSteps} ,",
            "</if>",
			"<if test='OrderStatus != null'>",
			"OrderStatus = #{OrderStatus} ,",
			"</if>",
			"<if test='isNeedPolicyTypeSupport != null'>",
			"IsNeedPolicyTypeSupport = #{isNeedPolicyTypeSupport} ,",
			"</if>",
			"<if test='faultType != null'>",
			"FaultType = #{faultType} ,",
			"</if>",
            "<if test='faultDealMethodAndConclusion != null'>",
            "FaultDealMethodAndConclusion = #{faultDealMethodAndConclusion} ,",
            "</if>",
			"<if test='Updator != null'>",
			"Updator = #{Updator} ,",
			"</if>",
			"<if test='UpdateTime != null'>",
            "UpdateTime = #{UpdateTime},",
            "</if>",
            "<if test='isFaultCode!=null'>",
            "  isFaultCode=#{isFaultCode},",
            "</if>",
            "<if test='FaultCode!=null '>",
            "  FaultCode=#{FaultCode},",
			"</if>",
			"<if test='BulletFlag!=null '>",
			"  BulletFlag=#{BulletFlag},",
			"</if>",
			"</set>",
			"where ID = #{ID}",
            "<if test='oldUpdateTime!=null'>",
            " and UpdateTime=#{oldUpdateTime}",
            "</if>",

            "</script>"})
	public int saveWorkOrderByUserAPPAppraise(Map<String, Object> map);

	//根据服务技师userid获取这个服务技师下所有工单状态在已出发，已到达，维修中的工单
	@Select("select distinct a.ID from WorkOrder_T a\r\n" +
			"inner join WorkOrderPrincipal_T b on a.ID = b.OrderId\r\n" +
			"where a.OrderStatus between 11 and 12 and b.UserId = #{UserId} and b.IsPrincipal = 1")
	public List<Map<String, Object>> getInServiceOrderListByUserId(Map<String, Object> map);

	//通过服务工单id获取未完成的诊断工单信息
	@Select("select top 1 * from WorkOrderDR_T where WFOrderId = #{workOrderId} and Status=0 ")
	Map<String,Object> getDRWorkOrderByWorkOrderId(long workOrderId);


	//通过服务工单id获取的诊断工单信息
	@Select("select top 1 * from WorkOrderDR_T where WFOrderId = #{workOrderId} ")
	Map<String,Object> getDRWorkOrderByOrderId(long workOrderId);

    //通过服务工单id获取的诊断工单信息---正常工单的id
    @Select("select top 1 * from WorkOrderDR_T where WFOrderId = #{workOrderId} and Flag=0 ")
    Map<String, Object> getDRWorkOrderByOrderIdAndFlag(long workOrderId);

    //修改工单状态sql
	@Update("update WorkOrder_T set OrderStatus = #{OrderStatus},Updator=#{Updator},UpdateTime = #{UpdateTime} where ID = #{OrderId} and  UpdateTime = #{OldUpdateTime}")
	int updateWorkOrderFinish(Map<String,Object> map);

	@Update("update WorkOrder_T set ServiceStationId = #{ServiceStationId},GuessDistance=#{GuessDistance},AssignStationTime=#{UpdateTime},\n" +
			"OrderStatus = 4,Updator = #{Updator},UpdateTime= #{UpdateTime} where ID = #{orderId} and UpdateTime=#{oldUpdateTime}")
	int updateWorkOrderAssignServerStation(Map<String,Object> map);

	//判断工单是否有区域工程师处理的状态
	@Select("select count(ID) from WorkOrderFlow_T where OrderId = #{orderId} and processStatus = 18")
	int isHaveEighteenOrderStutas(long orderId);

	//根据诊断工单获取所有的故障码和症状信息
	@Select("select * from DRFaultInfo_T where OrderId = #{drWorkOrderId} and Flag = 0")
	List<Map<String,Object>> getDRFaultInfoListByDRWorkOrderId(@Param("drWorkOrderId") long drWorkOrderId);

	//根据DRFaultInfo_T主键id获取所有执行过的方案编号
	@Select("select * from WorkOrderSolution_T where FCARecordId = #{drFaultInfoId} and Flag = 0 and IsWorked != 0")
	List<Map<String,Object>> getworkOrderSolutionByDRFaultInfoId(@Param("drFaultInfoId") long drFaultInfoId);

	@Update("update WorkOrder_T set TakeSteps = #{takeSteps} where ID=#{orderId}")
	int saveTakeSteps(@Param("takeSteps") String takeSteps,@Param("orderId") long orderId);

	@Select("select distinct wo.ID from WorkOrder_T wo\r\n" +
			"inner join WorkOrderPrincipal_T wof on wo.ID = wof.OrderId\r\n" +
			"where wo.OrderStatus in (11,12) and wof.UserId = #{userId} and wof.IsPrincipal = 1")
	List<Long> getRepairingOrderIdListByUserId(@Param("userId") Long userId);

	@Update("update WorkOrder_T set RealDistance = #{realDistance} where Flag = 0 and ID = #{orderId}")
	int updateRealDistance(@Param("realDistance") String realDistance,@Param("orderId") Long orderId);

	@Update("update WorkOrder_T set GuessDistance = #{guessDistance} where Flag = 0 and ID = #{orderId}")
	int updateGuessDistance(@Param("guessDistance") String guessDistance,@Param("orderId") Long orderId);

	@Update("update WorkOrder_T set GuessDistance = #{guessDistance},FastestDistance = #{fastestDistance},ShortestDistance = #{shortestDistance} " +
			"where Flag = 0 and ID = #{orderId}")
	int updateMultiDistance(@Param("guessDistance") String guessDistance,@Param("fastestDistance") String fastestDistance,
							@Param("shortestDistance") String shortestDistance,@Param("orderId") Long orderId);

    @Select("select top 20 CustomerName as customerName,CustomerPhone as customerPhone,CustomerCompanyName as customerCompanyName," +
            "Location as location,LocLat as locLat,LocLon as locLon \n" +
			"  from WorkOrder_T\n" +
			"  where ID in (\n" +
			"    select MAX(ID) from WorkOrder_T where ESN = #{ESN} and OrderChannel = #{companyId} group by CustomerName,CustomerPhone\n" +
			"  ) order by CreateTime desc")
	List<Map<String,Object>> getChannelCustomerInfoByESN(@Param("ESN") String ESN,@Param("companyId") Long companyId);

	@Select("select id, orderno, ordernocrm, orderchannel, ordersource, esn, vin, vic, enginetype, smn, oemid, oemname, customerid, customername, customerphone, loclon, loclat, location, auditlevel, currentlevel, customercomplaint, servicestationid, servicecarid, servicecarno, isoutside, guessdistance, realdistance, adjustdistance, assigntimeaudit, assignstationtime, refusetimestation, refusereasonstation, receivetimestation, assignengineertime, receivetimeengineer, refusetimeengineer, refusereasonengineer, departtime, arrivetime, secondout, diagnostictime, handleway, repairparts, principalid, comment, orderstatus, relorderid, canceltime, cancelreason, closetime, closereason, transfertime, transferreason, finishtime, doneinoneday, undonereason, flag, creator, createtime, updator, updatetime, deleter, deletetime, enginemsgid, relorderidold, markettype, application, warrantystartdate, workhours, workmileages, customertype, customercompanyname, customercompanyprovince, customercompanycity, locprovince, loccity, uploadtime, ordertype, isneedpolicytypesupport, faulttype, takesteps, goouttype, estimatedtime, faultdealmethodandconclusion, requesttype, contactname, contactphone, repairertype, faultlevel, serviceinitplan, ccssorderno, resolveremoteid, complainworkordertype, sizefailure, faultreason, fastestdistance, shortestdistance, isinsteadrepairs, servicesubtype, unifiedrepairno, faultcodes, symptomname, confirmmodifytime, locationisupdated, enginepurpose, engineseries, natureclaim, emergencymode, chassisnumber, healthexaminationcategory, realesn, gsn, mttag, salesservicetype, replacelon, replacelat, currentlon, currentlat, changepositionoperator, changepositiontime, currentlocation, newtargetlocation, bookkeepingtype, isshowstation, faultcode, isfaultcode, emissionlevel, amtno, warrantynature, faulthappentime from WorkOrder_T where OrderChannel =#{orderChannel} and ESN =#{ESN} and flag=0 and OrderStatus not in ( 15,16,31)")
	List<WorkOrderT> getListByESNAndChannel(@Param("ESN") String ESN,@Param("orderChannel") Long orderChannel);
	@Select("select top 20 CustomerName as customerName,CustomerPhone as customerPhone,CustomerCompanyName as customerCompanyName," +
			"Location as location,LocLat as locLat,LocLon as locLon \n" +
			"  from WorkOrder_T\n" +
			"  where ID in (\n" +
			"    select MAX(ID) from WorkOrder_T where ESN = #{ESN} and OrderChannel = #{companyId} and ServiceStationId = #{stationId} group by CustomerName,CustomerPhone\n" +
			"  ) order by CreateTime desc")
	List<Map<String, Object>> getChannelCustomerInfoByESNStationId(@Param("ESN") String ESN, @Param("companyId") Long companyId, @Param("stationId") long stationId);

	@Select("select top 20 CustomerName as customerName,CustomerPhone as customerPhone,CustomerCompanyName as customerCompanyName," +
			"Location as location,LocLat as locLat,LocLon as locLon \n" +
			"  from WorkOrder_T\n" +
			"  where ID in (\n" +
			"    select MAX(ID) from WorkOrder_T where AmtNo = #{amtNo} and OrderChannel = #{companyId} and ServiceStationId = #{stationId} group by CustomerName,CustomerPhone\n" +
			"  ) order by CreateTime desc")
	List<Map<String, Object>> getChannelCustomerInfoByAmtNoStationId(@Param("amtNo") String amtNo, @Param("companyId") Long companyId, @Param("stationId") long stationId);

	//根据crmNo获取工单
	@Select("select top 1 b.StationName,a.* from WorkOrder_T a\n" +
			"left join ServiceStation_T b on a.ServiceStationId = b.ID\n" +
			"where a.OrderNoCrm = #{orderNoCrm} and a.Flag = 0 order by ID desc")
	Map<String,Object> getWorkOrderByOrderNoCrm(@Param("orderNoCrm") String orderNoCrm);

	//根据crmNo获取工单
	@Select("select count(1) from WorkOrder_T where OrderNoCrm = #{orderNoCrm} and Flag = 0")
	int getcountByOrderNoCrm(@Param("orderNoCrm") String orderNoCrm);

	@Update({"<script>",
			"update WorkOrder_T set ",
			"<if test='orderSource != null and orderSource == 0'>",
			"ContactName = #{contactName} ,ContactPhone = #{contactPhone},",
			"</if>",
			"<if test='orderSource != null and orderSource == 1'>",
			"CustomerName = #{contactName} ,CustomerPhone = #{contactPhone},",
			"</if>",
            "CustomerCompanyName = #{customerCompanyName} ,",
            "CustomerComplaint = #{customerComplaint} ,",
			"OrderStatus = #{orderStatus} ,",
			"Updator = #{updator} ,",
			"UpdateTime = #{updateTime}",
			"where ID = #{orderId}",
			"<if test='oldUpdateTime!=null'>",
			" and UpdateTime=#{oldUpdateTime}",
			"</if>",
			"</script>"})
	int updateWorkOrderMsg(Map<String, Object> map);


	int updateByPrimaryKeySelective(Map record);


	//CCEC   技师点击提交诊断结果   不能开始维修    生成新工单时需要旧工单的信息
	@Select("select a.ID,a.OrderNoCrm,a.OrderChannel,a.OrderSource,a.ESN,a.VIN,a.OEMName,a.CustomerId,a.CustomerName,a.CustomerPhone,a.LocLon,a.LocLat,a.Location,a.CreateTime,\n" +
			"a.CustomerComplaint,a.EngineMsgId,a.WorkHours,a.WorkMileages,a.CustomerCompanyName,a.RequestType,a.ContactName,a.ContactPhone,a.RepairerType,a.FaultLevel,a.ComplainWorkOrderType\n" +
			"from WorkOrder_T  a \n" +
			"where a.ID = #{orderId}")
	Map<String,Object> getCCECOldWorkOrderMsgById(@Param("orderId") long orderId);

	/**
	 * 获取技师可升级的服务工单
	 */
	List<GetWorkOrderListResponse> getTechnicianWorkOrderListForEscalation(GetWorkOrderListRequest getWorkOrderListRequest);

	/**
	 * 获取区域工程师可升级的服务工单
	 */
	List<GetWorkOrderListResponse> getFieldEngineerWorkOrderListForEscalation(GetWorkOrderListRequest getWorkOrderListRequest);

    UserT getFieldEngineerByWorkOrderId(@Param("orderId") Long orderId);


	List<GetWorkOrderListResponse> getWorkOrderListForEscalationById(@Param("orderId")Long orderId);
	List<WorkOrderT> selectListByStationAndStatus(@Param("orderChannel") Long orderChannel,@Param("serviceStationId") Long serviceStationId,@Param("orderStatus") Integer orderStatus, @Param("keyword") String keyword);

	@Select("select * from WorkOrder_T where Flag = 0 and OrderChannel = #{orderChannel} and OrderStatus = #{orderStatus} order by CreateTime desc")
	List<WorkOrderT> selectListByStatus(@Param("orderChannel") Long orderChannel,@Param("orderStatus") Integer orderStatus);

	//根据服务站id获取dbu所有待派技师的工单
    @Select("select a.ID as orderId,a.OrderNo as orderNo,a.CreateTime as createTime,a.CustomerComplaint as customerComplaint,a.ESN as esn,b.DValue as orderSource from WorkOrder_T a\n" +
			"left join Dictionaries_T b on a.OrderSource = b.DInt and b.DTableName = 'OrderSource'\n" +
			"where a.OrderStatus = 6 and ServiceStationId = #{serviceStationId} and OrderChannel = 1")
    List<Map<String,Object>> getWaitAssignTechnicianOrderList(@Param("serviceStationId") long serviceStationId);

    @Select("select a.ID as orderId,a.OrderNo as orderNo,a.ESN as esn,b.SMN as smn,a.OEMName as oemName,b.MarketType as marketType,a.RealESN as realESN,\n" +
			"b.Application as application,a.WorkHours as workHours,a.WorkMileages as workMileages,a.CreateTime as repairsTime,\n" +
			"a.CustomerName as customerName,a.CustomerPhone as customerPhone,c.Address as serviceStationAddress,a.Location as repairsLocation,\n" +
			"a.CustomerComplaint as customerComplaint,a.LocLat as repairsLocLat,a.LocLon as repairsLocLon,c.PositionLat as serviceStationLat,c.PositionLon as serviceStationLon\n" +
			"from WorkOrder_T a\n" +
			"left join EngineMsg b on a.ESN = b.ESN\n" +
			"left join ServiceStation_T c on a.ServiceStationId = c.ID\n" +
			"where a.ID = #{orderId}")
	Map<String,Object> getWorkOrderMsgById(@Param("orderId")long orderId);


    //修改工单状态通用sql
    @Update("update WorkOrder_T set OrderStatus = #{orderStatus},Updator = #{userId},UpdateTime = #{currentTime} where ID = #{orderId} and UpdateTime = #{oldUpdateTime}")
	int updateOrderMsg(Map<String, Object> map);

    //根据技师id和工单渠道获取该技师名下是否有已出发，未到达的服务工单
    @Select("select count(ID) from WorkOrder_T \n" +
            "where OrderStatus = 10 and Updator = #{userId} and OrderChannel = (select OrderChannel from WorkOrder_T where ID = #{orderId})")
    int getHasBeenSetOutCountByUserId(@Param("userId")long userId,@Param("orderId")long orderId);


    //根据工单编号获取工单信息包括服务渠道信息
    @Select("select top 1 b.CompanyNo,a.* from WorkOrder_T a\n" +
            "inner join Company_T b on a.OrderChannel = b.ID\n" +
            "where OrderNo = #{orderNo}")
    Map<String,Object> getWorkOrderAndCompanyMsgByOrderNo(@Param("orderNo")String orderNo);


    //移动技师sql  获取服务工单相关里程信息
    List<Map<String, Object>> getWorkOrderInfoListByIds(List<Long> list);

    int updateEntityById(WorkOrderT workOrder);

	int updateMaintenancePointByOrderNo(Map<String,Object> map);

	int updateWorkOrderById(WorkOrderT workOrder);

	int updateServiceSubtypeByOrderNo(Map<String, Object> map);

    //根据esn获取某渠道下某些状态下的工单编号
    @Select(" <script> select ISNULL(stuff((select ','+  a.OrderNo from WorkOrder_T a where Flag = 0 and OrderChannel = #{orderChannel} and OrderStatus not in<foreach collection='orderStatusStr' item='item' open='(' separator=',' close=')'>#{item} </foreach> and ESN = #{esn} for xml path('')),1,1,''),'') as workOrderNo </script>")
    Map<String, Object> getOrderMsgByESN(@Param("orderChannel") long orderChannel, @Param("orderStatusStr") List<Integer> orderStatusStr, @Param("esn") String esn);

	WorkOrderT selectWorkOrderByOrderNo(String orderNo);

	List<WorkOrderT> selectWorkOrderByOrderNoList(@Param("orderNoList") List<String> orderNoList);

	int updateWorkOrderLocationById(WorkOrderT workOrder);

	int updateStatusByOrderNo(@Param("workOrderList") List<String> workOrderList, @Param("status") Integer status);

	@Select("select count(*) from WorkOrder_T where OrderChannel=#{orderChannel} and OrderNo=#{orderNo}")
	int getWorkOrderIsExistence(@Param("orderNo") String orderNo, @Param("orderChannel") String orderChannel);

	@Select(" update WorkOrder_T set RealESN = #{realESN} where id = #{id}")
	void updatRealESNById(WorkOrderT workOrderT1);

	//根据esn，当天日期和工单状态，获取当天该esn是否存在ccec400审核通过的状态
	//待服务商接单,服务商已拒单,待派服务技师,待服务技师接单,技师已接单,技师已拒单 ,已出发,已到达,维修中,待用户评价 ,服务完成,诊断中,诊断完成,待400回访
	@Select("select top 1 count(1) from WorkOrder_T b\n" +
            "where b.Flag = 0 and b.ESN = #{esn} and b.ID in(\n" +
            "select distinct a.OrderId from WorkOrderFlow_T a\n" +
            "where a.CreateTime like concat('%',#{currentTime},'%')   and \n" +
            "a.processStatus in(4,5,6,7,8,9,10,11,12,13,14,26,27,32) and a.Flag = 0\n" +
            ")")
	int getCCECPassCountByEsn(@Param("esn") String esn,@Param("currentTime") String currentTime);

	@Select("select top 1 isnull(SMN,'')  from WorkOrder_T where Creator=#{creator}  order by id desc")
    String getLastSMNWorkorder(@Param("creator") Long creator);

	@Select("select top 1 isnull(SMN,'') from WorkOrder_T wt where ID= (select top 1 OrderId from WorkOrderPrincipal_T where UserId=#{userId} and Flag = 0  order by CreateTime desc)")
	String getLastSMNWorkorderByPrincipal(@Param("userId") Long userId);


	@Update("update WorkOrder_T set EmissionLevel = #{EmissionLevel} where Flag = 0 and ID = #{ID}")
	int updateEmissionLevel(Map<String,Object> map);

    List<WorkOrderT> getWorkOrderByStationAndEsn(@Param("stationId")Long stationId, @Param("list")List<String> esnList);
}
